package com.taocyb.framework.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 安全工具类包含 (1.密码盐值加密)
 */
public class SecurityUtils {
	private static final String DEFAULT_DOMAIN = "taocyb";
	
	private final static SecureRandom random = new SecureRandom();

	/**
	 * 生成hex编码加密盐值
	 */
	public static String hexSalt(){
		return Hex.encodeHexString(random.generateSeed(8));
	}
	
	/**
	 * sha1加密 
	 * @param password 明文密码
	 * @param salt	   Hex编码加密盐值
	 */
	public static String sha1Password(String password, String salt){
		try {
			MessageDigest digest = DigestUtils.getSha1Digest();
			
			if(StringUtils.isNotBlank(salt)){
				byte[] hashsalt = Hex.decodeHex(salt.toCharArray());
				digest.update(hashsalt);
			}
			
			byte[] hashPassword = digest.digest(password.getBytes());
			return  Hex.encodeHexString(hashPassword);
		} catch (DecoderException e) {
			throw Exceptions.unchecked(e);
		}
	}
	
	public static String encryptCookieValueMd5(String loginName, String password){
		String value = (loginName + "_" + password + "_" + DEFAULT_DOMAIN);
		return DigestUtils.md5Hex(value);
	}
	
	/**
	 * 加密存储在cookie中的用户信息
	 * @param loginName 	用户账号
	 * @param password		用户密码
	 * @param expiry		有效时长（单位:秒）
	 */
	public static String encryptCookieValueBase64(String loginName, String password, int expiry){
		String md5Value = encryptCookieValueMd5(loginName, password);
		long validTime = System.currentTimeMillis() + expiry * 1000;
		String cookieValue = (loginName + ":" + validTime + ":" + md5Value);
		String hassCookieValue = new String(Base64.encodeBase64(cookieValue.getBytes()));
		return hassCookieValue;
	}
}
